import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as path;
import 'package:image_picker/image_picker.dart';

import '../serve/file_serve.dart';
import '../serve/upload_service.dart';
import 'screen_shot_serve.dart';
import 'tina_dart/BaseAPI.dart';
import 'dify_datasets.dart';

/// 智能悬浮球服务事件类型
enum SmartFloatingBallEventType {
  screenshotRequested,
  screenshotResult,
  screenshotSuccess,
  screenshotSuccessWithNavigation,
  persistentCaptureReady,
  persistentCapturePermissionDenied,
  persistentCapturePermissionError,
  projectionStopped,
  serviceStatusChanged,
}

/// 智能悬浮球事件数据
class SmartFloatingBallEvent {
  final SmartFloatingBallEventType type;
  final Map<String, dynamic> data;
  final DateTime timestamp;

  SmartFloatingBallEvent({
    required this.type,
    required this.data,
    DateTime? timestamp,
  }) : timestamp = timestamp ?? DateTime.now();

  factory SmartFloatingBallEvent.screenshotRequested({
    String? source,
    DateTime? timestamp,
  }) {
    return SmartFloatingBallEvent(
      type: SmartFloatingBallEventType.screenshotRequested,
      data: {
        'source': source ?? 'unknown',
      },
      timestamp: timestamp,
    );
  }

  factory SmartFloatingBallEvent.screenshotResult({
    required bool success,
    String? imagePath,
    String? error,
    DateTime? timestamp,
  }) {
    return SmartFloatingBallEvent(
      type: SmartFloatingBallEventType.screenshotResult,
      data: {
        'success': success,
        'imagePath': imagePath,
        'error': error,
      },
      timestamp: timestamp,
    );
  }

  factory SmartFloatingBallEvent.screenshotSuccess({
    required String imagePath,
    bool navigateToUpload = false,
    DateTime? timestamp,
  }) {
    return SmartFloatingBallEvent(
      type: SmartFloatingBallEventType.screenshotSuccessWithNavigation,
      data: {
        'imagePath': imagePath,
        'navigateToUpload': navigateToUpload,
      },
      timestamp: timestamp,
    );
  }

  factory SmartFloatingBallEvent.persistentCaptureReady({
    DateTime? timestamp,
  }) {
    return SmartFloatingBallEvent(
      type: SmartFloatingBallEventType.persistentCaptureReady,
      data: {},
      timestamp: timestamp,
    );
  }

  factory SmartFloatingBallEvent.persistentCapturePermissionDenied({
    String? reason,
    DateTime? timestamp,
  }) {
    return SmartFloatingBallEvent(
      type: SmartFloatingBallEventType.persistentCapturePermissionDenied,
      data: {
        'reason': reason ?? 'Permission denied',
      },
      timestamp: timestamp,
    );
  }

  factory SmartFloatingBallEvent.persistentCapturePermissionError({
    required String error,
    DateTime? timestamp,
  }) {
    return SmartFloatingBallEvent(
      type: SmartFloatingBallEventType.persistentCapturePermissionError,
      data: {
        'error': error,
      },
      timestamp: timestamp,
    );
  }

  factory SmartFloatingBallEvent.projectionStopped({
    required String reason,
    bool needReauthorization = true,
    DateTime? timestamp,
  }) {
    return SmartFloatingBallEvent(
      type: SmartFloatingBallEventType.projectionStopped,
      data: {
        'reason': reason,
        'needReauthorization': needReauthorization,
      },
      timestamp: timestamp,
    );
  }

  factory SmartFloatingBallEvent.serviceStatusChanged({
    required bool isRunning,
    Map<String, dynamic>? status,
    DateTime? timestamp,
  }) {
    return SmartFloatingBallEvent(
      type: SmartFloatingBallEventType.serviceStatusChanged,
      data: {
        'isRunning': isRunning,
        'status': status ?? {},
      },
      timestamp: timestamp,
    );
  }
}

/// 智能悬浮球服务 - Android 14兼容版本
class SmartFloatingBallService {
  static const MethodChannel _channel = MethodChannel(
    'com.example.patchouli_knowledge/smart_floating_ball',
  );

  static final StreamController<SmartFloatingBallEvent> _eventController =
      StreamController<SmartFloatingBallEvent>.broadcast();

  static Stream<SmartFloatingBallEvent> get eventStream => _eventController.stream;

  static bool _isInitialized = false;
  static bool _isServiceRunning = false;
  static bool _isPersistentCaptureReady = false;
  static ScreenShotServe? _screenShotServe;

  /// 设置OCR服务
  static Future<void> setScreenShotServe(ScreenShotServe screenShotServe) async {
    _screenShotServe = screenShotServe;
    print('SmartFloatingBallService: OCR服务已设置');
  }

  /// 获取OCR服务
  static ScreenShotServe? getScreenShotServe() {
    return _screenShotServe;
  }

  /// 初始化服务
  static Future<void> initialize() async {
    if (_isInitialized) return;

    _channel.setMethodCallHandler(_handleMethodCall);
    _isInitialized = true;

    print('SmartFloatingBallService initialized - Android 14 compatible mode');
  }

  /// 处理来自原生端的方法调用
  static Future<void> _handleMethodCall(MethodCall call) async {
    print('SmartFloatingBallService received: ${call.method}');

    try {
      switch (call.method) {
        case 'onScreenshotRequested':
          _handleScreenshotRequested(call.arguments);
          break;
        case 'onScreenshotResult':
          _handleScreenshotResult(call.arguments);
          break;
        case 'onScreenshotSuccess':
          _handleScreenshotSuccess(call.arguments);
          break;
        case 'onPersistentCaptureReady':
          _handlePersistentCaptureReady(call.arguments);
          break;
        case 'onPersistentCapturePermissionDenied':
          _handlePersistentCapturePermissionDenied(call.arguments);
          break;
        case 'onPersistentCapturePermissionError':
          _handlePersistentCapturePermissionError(call.arguments);
          break;
        case 'onProjectionStopped':
          _handleProjectionStopped(call.arguments);
          break;
        default:
          print('Unknown method call: ${call.method}');
      }
    } catch (e) {
      print('Error handling method call ${call.method}: $e');
    }
  }

  /// 处理截图请求
  static void _handleScreenshotRequested(dynamic arguments) {
    final Map<String, dynamic> args = Map<String, dynamic>.from(arguments ?? {});
    
    final event = SmartFloatingBallEvent.screenshotRequested(
      source: args['source'],
      timestamp: args['timestamp'] != null 
          ? DateTime.fromMillisecondsSinceEpoch(args['timestamp'])
          : null,
    );

    _eventController.add(event);
    print('Screenshot requested from: ${args['source']}');
  }

  /// 处理截图结果
  static void _handleScreenshotResult(dynamic arguments) {
    final Map<String, dynamic> args = Map<String, dynamic>.from(arguments ?? {});
    
    final event = SmartFloatingBallEvent.screenshotResult(
      success: args['success'] ?? false,
      imagePath: args['imagePath'],
      error: args['error'],
      timestamp: args['timestamp'] != null 
          ? DateTime.fromMillisecondsSinceEpoch(args['timestamp'])
          : null,
    );

    _eventController.add(event);
    print('Screenshot result: success=${args['success']}, path=${args['imagePath']}');
  }

  /// 处理截图成功（带导航）
  static void _handleScreenshotSuccess(dynamic arguments) {
    final Map<String, dynamic> args = Map<String, dynamic>.from(arguments ?? {});
    
    final event = SmartFloatingBallEvent.screenshotSuccess(
      imagePath: args['imagePath'] ?? '',
      navigateToUpload: args['navigateToUpload'] ?? false,
      timestamp: args['timestamp'] != null 
          ? DateTime.fromMillisecondsSinceEpoch(args['timestamp'])
          : null,
    );

    _eventController.add(event);
    print('Screenshot success with navigation: path=${args['imagePath']}');
  }

  /// 处理持久截屏准备就绪
  static void _handlePersistentCaptureReady(dynamic arguments) {
    _isPersistentCaptureReady = true;
    
    final event = SmartFloatingBallEvent.persistentCaptureReady(
      timestamp: arguments?['timestamp'] != null 
          ? DateTime.fromMillisecondsSinceEpoch(arguments['timestamp'])
          : null,
    );

    _eventController.add(event);
    print('Persistent capture ready - Android 14 compatible mode');
  }

  /// 处理持久截屏权限被拒绝
  static void _handlePersistentCapturePermissionDenied(dynamic arguments) {
    _isPersistentCaptureReady = false;
    final Map<String, dynamic> args = Map<String, dynamic>.from(arguments ?? {});
    
    final event = SmartFloatingBallEvent.persistentCapturePermissionDenied(
      reason: args['reason'],
      timestamp: args['timestamp'] != null 
          ? DateTime.fromMillisecondsSinceEpoch(args['timestamp'])
          : null,
    );

    _eventController.add(event);
    print('Persistent capture permission denied: ${args['reason']}');
  }

  /// 处理持久截屏权限错误
  static void _handlePersistentCapturePermissionError(dynamic arguments) {
    _isPersistentCaptureReady = false;
    final Map<String, dynamic> args = Map<String, dynamic>.from(arguments ?? {});
    
    final event = SmartFloatingBallEvent.persistentCapturePermissionError(
      error: args['error'] ?? 'Unknown error',
      timestamp: args['timestamp'] != null 
          ? DateTime.fromMillisecondsSinceEpoch(args['timestamp'])
          : null,
    );

    _eventController.add(event);
    print('Persistent capture permission error: ${args['error']}');
  }

  /// 处理MediaProjection停止事件
  static void _handleProjectionStopped(dynamic arguments) {
    _isPersistentCaptureReady = false;
    final Map<String, dynamic> args = Map<String, dynamic>.from(arguments ?? {});
    
    final event = SmartFloatingBallEvent.projectionStopped(
      reason: args['reason'] ?? 'MediaProjection stopped',
      needReauthorization: args['needReauthorization'] ?? true,
      timestamp: args['timestamp'] != null 
          ? DateTime.fromMillisecondsSinceEpoch(args['timestamp'])
          : null,
    );

    _eventController.add(event);
    print('MediaProjection stopped: ${args['reason']}');
  }

  /// 启动智能悬浮球服务
  static Future<bool> startService() async {
    try {
      await initialize();
      final result = await _channel.invokeMethod('startSmartFloatingBall');
      _isServiceRunning = result ?? false;
      
      if (_isServiceRunning) {
        print('Smart floating ball service started successfully');
        _eventController.add(SmartFloatingBallEvent.serviceStatusChanged(
          isRunning: true,
        ));
      }
      
      return _isServiceRunning;
    } catch (e) {
      print('Failed to start smart floating ball service: $e');
      return false;
    }
  }

  /// 停止智能悬浮球服务
  static Future<bool> stopService() async {
    try {
      final result = await _channel.invokeMethod('stopSmartFloatingBall');
      _isServiceRunning = false;
      _isPersistentCaptureReady = false;
      
      print('Smart floating ball service stopped');
      _eventController.add(SmartFloatingBallEvent.serviceStatusChanged(
        isRunning: false,
      ));
      
      return result ?? true;
    } catch (e) {
      print('Failed to stop smart floating ball service: $e');
      return false;
    }
  }

  /// 检查服务是否运行
  static Future<bool> isServiceRunning() async {
    try {
      final result = await _channel.invokeMethod('isSmartFloatingBallRunning');
      _isServiceRunning = result ?? false;
      return _isServiceRunning;
    } catch (e) {
      print('Failed to check service status: $e');
      return false;
    }
  }

  /// 初始化持久截屏功能
  static Future<bool> initializePersistentCapture() async {
    try {
      print('Initializing persistent capture - Android 14 compatible mode');
      final result = await _channel.invokeMethod('initPersistentCapture');
      return result ?? false;
    } catch (e) {
      print('Failed to initialize persistent capture: $e');
      return false;
    }
  }

  /// 检查持久截屏是否运行
  static Future<bool> isPersistentCaptureRunning() async {
    try {
      final result = await _channel.invokeMethod('isPersistentCaptureRunning');
      return result ?? false;
    } catch (e) {
      print('Failed to check persistent capture status: $e');
      return false;
    }
  }

  /// 停止持久截屏服务
  static Future<bool> stopPersistentCapture() async {
    try {
      final result = await _channel.invokeMethod('stopPersistentCapture');
      _isPersistentCaptureReady = false;
      return result ?? true;
    } catch (e) {
      print('Failed to stop persistent capture: $e');
      return false;
    }
  }

  /// 获取服务状态
  static Map<String, dynamic> getServiceStatus() {
    return {
      'isInitialized': _isInitialized,
      'isServiceRunning': _isServiceRunning,
      'isPersistentCaptureReady': _isPersistentCaptureReady,
      'timestamp': DateTime.now().millisecondsSinceEpoch,
    };
  }

  /// 释放资源
  static void dispose() {
    _eventController.close();
    _isInitialized = false;
    _isServiceRunning = false;
    _isPersistentCaptureReady = false;
    print('SmartFloatingBallService disposed');
  }
} 